import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, Tag, message, Spin, Input, Select } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons';
import { stockApi, StockModel } from '../services/stockApi';

const { Option } = Select;

const StockList = ({ onViewStock }) => {
  const [stocks, setStocks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear()); // 默认当前年份

  // 生成年份选项（当前年份及前5年）
  const generateYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = 0; i <= 5; i++) {
      years.push(currentYear - i);
    }
    return years;
  };

  // 加载股票列表
  const loadStocks = async () => {
    setLoading(true);
    try {
      const data = await stockApi.getAllStocks(selectedYear);
      const minMaxPrice = Math.min(...data.map(stock => stock.max_price || 0));
      const minLiqa = Math.min(...data.map(stock => stock.liqa_share || 0));
      const maxDividend = Math.max(...data.map(stock => stock.dividend || 0));
      const toIdeaValue = (maxPrice = 0, liqa =0, dividend = 0) => {
        const x = (maxPrice - minMaxPrice) ;
        const y = (liqa - minLiqa) ;
        const z = (dividend - maxDividend) ;
        console.log(x,y,z,maxPrice,liqa/1000000,dividend)
        return Math.sqrt(x * x + y * y + z * z);
      }

      setStocks(data.map(stock => ({
        ...stock,
        idea_value_front: toIdeaValue(stock.max_price || 0, stock.liqa_share || 0, stock.dividend || 0)
      })).sort((a, b) => b.idea_value_front - a.idea_value_front) || []);
      message.success(`成功加载 ${data?.length || 0} 只股票 (${selectedYear}年)`);
    } catch (error) {
      console.error('加载股票列表失败:', error);
      message.error('加载股票列表失败，请检查后端服务是否启动');
      setStocks([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadStocks();
  }, [selectedYear]);

  // 过滤股票列表
  const filteredStocks = stocks.filter(stock => {
    if (!searchText) return true;
    
    const searchLower = searchText.toLowerCase();
    return (
      stock.no.toLowerCase().includes(searchLower) ||
      stock.market.toLowerCase().includes(searchLower) ||
      StockModel.formatStockCode(stock.market, stock.no).toLowerCase().includes(searchLower)
    );
  });

  // 表格列定义
  const columns = [
    {
      title: '股票代码',
      dataIndex: 'stock_no',
      key: 'stock_no',
      width: 120,
      render: (text, record) => (
        <Space>
          <Tag color={record.market === 'SH' ? '#f50' : '#2db7f5'}>
            {record.market}
          </Tag>
          <strong>{text}</strong>
        </Space>
      ),
      sorter: (a, b) => a.stock_no.localeCompare(b.no),
    },
    {
      title: '股票名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (text, record) => (
        <span>
          {record.stock_market === 'sh' ? '上证' : '深证'} {text}
        </span>
      ),
    },
    {
      title: '开盘价',
      dataIndex: 'open_price',
      key: 'open_price',
      width: 100,
      render: (price) => StockModel.formatPrice(price),
      sorter: (a, b) => (a.open_price || 0) - (b.open_price || 0),
    },
    {
      title: '收盘价',
      dataIndex: 'close_price',
      key: 'close_price',
      width: 100,
      render: (price) => StockModel.formatPrice(price),
      sorter: (a, b) => (a.close_price || 0) - (b.close_price || 0),
    },
    {
      title: '涨跌幅',
      key: 'change_rate',
      width: 100,
      render: (_, record) => {
        const change = StockModel.calculateChangeRate(record.close_price, record.open_price);
        const color = change.isPositive ? '#ff4d4f' : '#52c41a';
        const symbol = change.isPositive ? '+' : '-';
        
        return (
          <span style={{ color, fontWeight: 'bold' }}>
            {symbol}{change.rate}%
          </span>
        );
      },
      sorter: (a, b) => {
        const changeA = StockModel.calculateChangeRate(a.close_price, a.open_price);
        const changeB = StockModel.calculateChangeRate(b.close_price, b.open_price);
        return (changeA.rate * (changeA.isPositive ? 1 : -1)) - 
               (changeB.rate * (changeB.isPositive ? 1 : -1));
      },
    },
    {
      title: '最高价',
      dataIndex: 'max_price',
      key: 'max_price',
      width: 100,
      render: (price) => StockModel.formatPrice(price),
      sorter: (a, b) => (a.max_price || 0) - (b.max_price || 0),
    },
    {
      title: '最低价',
      dataIndex: 'min_price',
      key: 'min_price',
      width: 100,
      render: (price) => StockModel.formatPrice(price),
      sorter: (a, b) => (a.min_price || 0) - (b.min_price || 0),
    },
    {
      title: '总股本',
      dataIndex: 'total_share',
      key: 'total_share',
      width: 120,
      render: (shares) => StockModel.formatShares(shares),
      sorter: (a, b) => (a.total_share || 0) - (b.total_share || 0),
    },
    {
      title: '流通股本',
      dataIndex: 'liqa_share',
      key: 'liqa_share',
      width: 120,
      render: (shares) => StockModel.formatShares(shares),
      sorter: (a, b) => (a.liqa_share || 0) - (b.liqa_share || 0),
    },
    {
      title: '股息',
      dataIndex: 'dividend',
      key: 'dividend',
      width: 80,
      render: (dividend) => dividend ? `¥${dividend.toFixed(2)}` : '--',
      sorter: (a, b) => (a.dividend || 0) - (b.dividend || 0),
    },
    {
      title: '投资价值',
      dataIndex: 'idea_value',
      key: 'idea_value',
      width: 100,
      render: (value) => {
        if (value === null || value === undefined) return '--';
        
        // 根据值的大小设置不同的颜色
        let color = '#52c41a'; // 绿色（低值）
        if (value > 0.5) color = '#fa8c16'; // 橙色（中值）
        if (value > 0.8) color = '#ff4d4f'; // 红色（高值）
        
        return (
          <Tag color={color}>
            {value.toFixed(2)}
          </Tag>
        );
      },
      sorter: (a, b) => (a.idea_value || 0) - (b.idea_value || 0),
    },
    ,
    {
      title: '投资价值(前端计算)',
      dataIndex: 'idea_value_front',
      key: 'idea_value_front',
      width: 100,
      render: (value) => {
        if (value === null || value === undefined) return '--';
        
        // 根据值的大小设置不同的颜色
        let color = '#52c41a'; // 绿色（低值）
        if (value > 0.5) color = '#fa8c16'; // 橙色（中值）
        if (value > 0.8) color = '#ff4d4f'; // 红色（高值）
        
        return (
          <Tag color={color}>
            {value.toFixed(2)}
          </Tag>
        );
      },
      sorter: (a, b) => (a.idea_value_front || 0) - (b.idea_value_front || 0),
    },

    
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Button 
          type="link" 
          icon={<EyeOutlined />}
          onClick={() => onViewStock(record)}
        >
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <Card 
      title="股票列表" 
      extra={
        <Space>
          <Select
            value={selectedYear}
            onChange={setSelectedYear}
            style={{ width: 100 }}
            placeholder="选择年份"
          >
            {generateYearOptions().map(year => (
              <Option key={year} value={year}>{year}年</Option>
            ))}
          </Select>
          <Input
            placeholder="搜索股票代码或市场"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 200 }}
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={loadStocks}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      }
    >
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={filteredStocks}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
          size="middle"
        />
      </Spin>
    </Card>
  );
};

export default StockList;